package com.example.esp8266.Main.Main_Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.esp8266.Equipment.Equipment_CtrlActivity;
import com.example.esp8266.Library.MQTT.MQTT_Depend;
import com.example.esp8266.R;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.Objects;

public class Home_Fragment extends Fragment
        implements View.OnClickListener{

    private View root;
    private int deviceCounts;
    private String user_name_sql,Common_Device_1,Common_Device_2,Common_Device_3;
    String TAG = "MQTT_Client";
    String server_ip ="",server_port = "";
    MQTT_Depend mqtt;
    private boolean MQTT_Status = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            deviceCounts = args.getInt("device_counts", 0);
            user_name_sql = args.getString("user_name_sql", "游客").trim();
        }

        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            server_ip = sharedPreferences.getString("server_ip",null);
            server_port = sharedPreferences.getString("server_port",null);
            Common_Device_1 = sharedPreferences.getString("collection_1",null);
            Common_Device_2 = sharedPreferences.getString("collection_2",null);
            Common_Device_3 = sharedPreferences.getString("collection_3",null);
        } else {
            Log.e("Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }

        if (server_ip != null) {
            // 在 Fragment 中执行 MQTT 连接
            Thread connectThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    // 在线程中连接 MQTT 服务器
                    mqtt = new MQTT_Depend(server_ip, server_port, "PC_TEST", "SYSTEM", "PC_1", "sxc789426", new MqttCallback() {
                        // mqtt回调函数

                        @Override
                        public void connectionLost(Throwable cause) {
                            Log.d(TAG,"connectionLostException: " + cause.getMessage());
                        }

                        @Override
                        public void messageArrived(String topic, MqttMessage message) throws Exception {
                            String messageStr=new String(message.getPayload());
                            if (Objects.equals(messageStr.trim(),"ESP8266_1.OK!")){
                                TextView status_1 = root.findViewById(R.id.device_1_status);
                                status_1.setText("在线");
                                MQTT_Status = true;
                                status_1.setBackgroundResource(R.drawable.gradient_background_6); // 使用setBackgroundResource方法设置背景资源
                            }
                            if (Objects.equals(messageStr.trim(),"ESP8266_1.OK?")){
                                MQTT_Status = true;
                            }
                            Log.d(TAG,topic+","+messageStr);
                        }

                        @Override
                        public void deliveryComplete(IMqttDeliveryToken token) {
                            Log.d(TAG,"deliveryComplete");
                        }
                    });
                }
            });
            connectThread.start();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.main_fragment, container, false);


        TextView Device_Name_1 = root.findViewById(R.id.device_main_1);
        TextView Device_Name_2= root.findViewById(R.id.device_main_2);
        TextView Device_Name_3 = root.findViewById(R.id.device_main_3);
        if(Common_Device_1 == null){
            Device_Name_1.setText("未添加设备");
        }
        else {
            Device_Name_1.setText(Common_Device_1.trim());
        }
        if(Common_Device_2 == null){
            Device_Name_2.setText("未添加设备");
        }
        else {
            Device_Name_2.setText(Common_Device_2.trim());
        }
        if(Common_Device_3 == null){
            Device_Name_3.setText("未添加设备");
        }
        else {
            Device_Name_3.setText(Common_Device_3.trim());
        }
        //初始化三收藏设备名

        if (deviceCounts != 0){
            TextView Device_list_in = root.findViewById(R.id.device_list_in);
            Device_list_in.setText("您好,"+ user_name_sql+ "\n" + "进入设备列表>");
            TextView Device_count = root.findViewById(R.id.device_count);
            Device_count.setText("绑定设备"+ deviceCounts + "/12台");
        }
        //初始化标题

        ImageView add_Common_equipment_1 = root.findViewById(R.id.add_Common_equipment_1);
        add_Common_equipment_1.setOnClickListener(this);
        TextView Common_equipment_1 = root.findViewById(R.id.Common_equipment_1);
        Common_equipment_1.setOnClickListener(this);
        return root;
    }

    @Override//调用OnClickListener接口处理各种单击事件
    public void onClick(View v) {
        if (v.getId() == R.id.add_Common_equipment_1){
            // 检查 getActivity() 是否返回的对象为非空
            if (getActivity() != null) {
                // 获取 SharedPreferences 对象
                SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("collection_1", ""); // 替换收藏1
                editor.apply();
            } else {
                Log.e("Fragment", "getActivity() returned null");
                // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
            }
        } else if (v.getId() == R.id.Common_equipment_1) {
            if(MQTT_Status) {
                Log.i(TAG,"Home,已断开与MQTT服务器的连接");
                mqtt.disconnect(MQTT_Status);
            }
            MQTT_Status = false;
            // 创建一个新的Intent，从当前Fragment关联的Activity启动DeviceCtrlActivity
            Intent intent = new Intent(getActivity(), Equipment_CtrlActivity.class);
            // 清除之前的所有Activity堆栈，确保登录界面是用户会见到的第一个界面
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在离开 MainFragment 时断开 MQTT 连接
        if(MQTT_Status) {
            Log.i(TAG,"Home,已断开与MQTT服务器的连接");
            mqtt.disconnect(MQTT_Status);
            MQTT_Status = false;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 在 Fragment 生命周期结束时执行的操作
        if(MQTT_Status) {
            Log.i(TAG,"Home,已断开与MQTT服务器的连接");
            mqtt.disconnect(MQTT_Status);
            MQTT_Status = false;
        }
    }
}